<template>
  <md-popup id="popup-container" v-model="value" position="bottom" :has-mask="true" prevent-scroll @hide="cancel">
    <md-popup-title-bar title="选择出发时间" ok-text="确认" cancel-text="取消" @confirm="confirm" @cancel="cancel"></md-popup-title-bar>
    <div class="container">
      <div class="hint">
        <img class="hint-icon" :src="require('@/assets/imgs/tk_ts.png')" />
        <div>
          <p v-html="getOrderTimeMsg"></p>
        </div>
        <!-- <div>
                    本线路服务时间为
                    <span class="theme-str">{{timeString}}</span>，请提前
                    <span class="theme-str">{{getBaoStartTimeConfig.preTime}}分钟</span>下单
        </div>-->
      </div>
      <md-picker
        class="picker"
        ref="picker"
        :data="getOrderTime"
        :cols="2"
        :default-index="pickerDefaultIndex"
        is-view
        is-cascade
        @initialed="onPickerInitialed"
        @change="onPickerConfirm"
      ></md-picker>
    </div>
  </md-popup>
</template>

<script>
import { Popup, PopupTitleBar, Picker } from 'mand-mobile';
import { mapGetters } from 'vuex';
import { BAO_CONFIRM_ORDER_TIME } from '@/store/mutations.types';
import Moment from 'moment';
import { extendMoment } from 'moment-range';
const moment = extendMoment(Moment);
moment.locale('zh-cn');

export default {
  name: 'time-selector',
  components: {
    [Popup.name]: Popup,
    [PopupTitleBar.name]: PopupTitleBar,
    [Picker.name]: Picker
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    type: {
      // 1:拼车、2:包车
      type: String,
      default: '1'
    },
    appendTo: {
      default: () => document.body
    }
  },
  data() {
    return {
      cancelStr: '取消',
      okStr: '下一步',
      pickerData: [],
      pickerDefaultIndex: [0, 0],
      pickerValue: '',
      pickerCols: 1,
      maxDays: 30,
      isCascade: false,
      confirmedTime: {
        timeStr: '',
        time: null
      },
      carFlag: '0',
      confirmed: {
        timeStr: '', // 时间字符串
        time: null, // moment对象
        wait: 0, // 等待分钟
        endTime: null
      }
    };
  },
  created() {
    // this.configDates();
  },
  methods: {
    confirm() {
      this.$store.commit(BAO_CONFIRM_ORDER_TIME, this.confirmed);
      this.value = false;
      this.$emit('submit');
    },
    cancel() {
      this.value = false;
      this.$emit('cancel');
    },
    // configDates() {
    //     let dateArr = [];
    //     let config = this.getBaoStartTimeConfig;
    //     for (let i = 0; i < this.maxDays; i++) {
    //         let date = moment()
    //             .seconds(0)
    //             .add(i, 'd');
    //         let str = '';
    //         switch (i) {
    //             case 0:
    //                 str = '今天';
    //                 break;
    //             case 1:
    //                 str = '明天';
    //                 break;
    //             case 2:
    //                 str = '后天';
    //                 break;
    //             default:
    //                 str = date.format('dddd');
    //         }
    //         let dateObj = {
    //             text: date.format('MMMDo') + str,
    //             value: date,
    //             children: []
    //         };
    //         let a = config.start.split(':');
    //         let b = config.end.split(':');
    //         let startHour = null;
    //         if (i === 0) {
    //             startHour = moment(date);
    //             startHour.add(config.preTime, 'm');
    //             let min = startHour.minutes();
    //             let gap = 0;
    //             if (min > 30) {
    //                 gap = 60 - min;
    //             } else {
    //                 gap = 30 - min;
    //             }
    //             startHour.add(gap, 'm');
    //         } else {
    //             startHour = moment(date)
    //                 .hour(a[0])
    //                 .minutes(a[1])
    //                 .seconds(0);
    //         }
    //         let endHour = moment(date)
    //             .hour(b[0])
    //             .minutes(b[1])
    //             .seconds(0);
    //         if (startHour.isAfter(endHour)) {
    //             continue;
    //         }
    //         const range = moment.range(startHour, endHour);
    //         let hours = Array.from(
    //             range.by('minute', {
    //                 step: 30
    //             })
    //         );
    //         hours.forEach(item => {
    //             let obj = {
    //                 text: item.format('HH:mm'),
    //                 value: item
    //             };
    //             dateObj.children.push(obj);
    //         });
    //         dateArr.push(dateObj);
    //     }
    //     this.pickerData.push(dateArr);
    // },
    onPickerInitialed() {
      this.getPickerValues();
      this.$refs.picker.refresh();
    },
    onPickerConfirm(columnIndex, itemIndex, value) {
      if (value) {
        this.getPickerValues();
      }
    },
    getPickerValues() {
      // let values = this.$refs.picker.getColumnValues();
      // let date = values[0].value;
      // let time = values[1].value;
      // this.confirmedTime.time = date
      //     .hours(time.hours())
      //     .minutes(time.minutes())
      //     .seconds(0)
      //     .milliseconds(0);
      // this.confirmedTime.timeStr = values[0].text + ' ' + values[1].text;
      // 新改的 从后台获取时间
      let pickerIndexs = this.$refs.picker.getColumnIndexs();
      if (this.getOrderTime[0].length > 0) {
        let obj = this.getOrderTime[0][pickerIndexs[0]];
        if (!obj) {
          return;
        }
        if (obj.children.length > 0) {
          let timeNumber = parseInt(obj.children[pickerIndexs[1]].value);
          this.confirmed.time = moment(timeNumber);
          this.confirmed.timeStr = this.confirmed.time.calendar(null, {
            sameDay: '[今天] HH:mm',
            nextDay: '[明天] HH:mm',
            nextWeek: 'MMMDodddd HH:mm',
            lastDay: '[昨天] HH:mm',
            lastWeek: 'MMMDodddd HH:mm',
            sameElse: 'MMMDodddd HH:mm'
          });
          this.carFlag = obj.children[pickerIndexs[1]].car_flag;
        } else {
          this.confirmed.time = null;
        }
      }
    }
  },
  mounted() {
    if (this.appendTo) {
      this.appendTo.appendChild(this.$el);
    }
  },
  beforeDestroy() {
    if (this.appendTo) {
      this.appendTo.removeChild(this.$el);
    }
  },
  computed: {
    ...mapGetters(['getOrderTime', 'getRoute', 'getBaoStartTimeConfig', 'getOrderTimeMsg']),
    timeString() {
      let config = this.getBaoStartTimeConfig;
      if (!config) {
        return '';
      }
      let startMoment = moment()
        .hours(config.start.split(':')[0])
        .minutes(config.start.split(':')[1])
        .seconds(0);
      let endMoment = moment()
        .hours(config.end.split(':')[0])
        .minutes(config.end.split(':')[1])
        .seconds(0);
      let startTime = startMoment.format('AHH:mm');
      let endTime = endMoment.format('AHH:mm');
      return startTime + '~' + endTime;
    }
  }
};
</script>

<style lang="stylus" scoped>
#popup-container {
  .container {
    background-color: #fff;
    height: 432px;

    .hint {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      height: 88px;
      font-size: 22px;
      color: color-text-caption;

      .hint-icon {
        width: 26px;
        height: 24px;
      }

      .theme-str {
        color: theme-color;
      }
    }
  }
}
</style>
